﻿using Castle.Core.Internal;
using Castle.Windsor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;

namespace MRSite.Common.Web
{
    public class ShanYuIocModule : IHttpModule
    {
        public void Dispose()
        {
            _containerAccessor.Container.Dispose();
        }

        public void Init(HttpApplication context)
        {
            _application = context;
            _containerAccessor = (IContainerAccessor)context;
            _application.PreRequestHandlerExecute += PreRequestHandler;
        }

        private void PreRequestHandler(object sender, EventArgs e)
        {
            var current = _application.Context.CurrentHandler as Page;
            if (current != null)
            {
                InjectPropertiesOn(current);
                current.InitComplete += delegate { InjectUserControls(current); };
            }
        }

        private void InjectUserControls(Control parent)
        {
            if (parent.Controls != null)
            {
                foreach (Control control in parent.Controls)
                {
                    if (control is UserControl)
                    {
                        InjectPropertiesOn(control);
                    }
                    InjectUserControls(control);
                }
            }
        }

        private void InjectPropertiesOn(Control current)
        {
            var properties = current.GetType().GetProperties();
            foreach (var property in properties)
            {
                var attributes = property.GetCustomAttributes(typeof(InjectAttribute), false);
                if (!attributes.IsNullOrEmpty())
                {
                    var value = _containerAccessor.Container.Resolve(property.PropertyType);
                    property.SetValue(current, value);
                }
            }
        }

        private HttpApplication _application;
        private IContainerAccessor _containerAccessor;
    }
}
